package com.hyrluntan.forum.controller;

import com.hyrluntan.forum.common.AppResult;
import com.hyrluntan.forum.common.ResultCode;
import com.hyrluntan.forum.config.AppConfig;
import com.hyrluntan.forum.model.Article;
import com.hyrluntan.forum.model.Board;
import com.hyrluntan.forum.model.User;
import com.hyrluntan.forum.services.IArticleService;
import com.hyrluntan.forum.services.IBoardService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "文章接口")
@Slf4j
@RestController
@RequestMapping("/article")
public class ArticleController {
    @Resource
    private IArticleService articleService;
    @Resource
    private IBoardService boardService;

    /***
     * 发布新帖子
     * @param request 请求
     * @param boardId 板块id
     * @param title 文章标题
     * @param content 帖子内容
     * @return
     */
    @ApiOperation("发布新帖")
    @PostMapping("/create")
    public AppResult create (HttpServletRequest request,
                             @ApiParam(value = "版块Id") @RequestParam(value = "boardId") @NonNull Long boardId,
                             @ApiParam(value = "⽂章标题") @RequestParam(value = "title") @NonNull String title,
                             @ApiParam(value = "帖⼦内容") @RequestParam(value = "content") @NonNull String content) {
        // 获取⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() == 1)
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        // 板块校验
        Board board = boardService.selectById(boardId.longValue());
        if(board==null||board.getDeleteState()==1||board.getState()==1){
            log.warn(ResultCode.FAILED_BOARD_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_BOARD_BANNED);
        }
        // 构造帖⼦对象
        Article article = new Article();
        article.setBoardId(boardId);
        article.setUserId(user.getId());
        article.setTitle(title);
        article.setContent(content);
        // 调⽤业务层
        articleService.create(article);
        // 返回结果
        return AppResult.success();
    }

    /**
     * 根据版块Id查询帖⼦列表
     *
     * @param boardId 版块Id
     * @return 指定版块的帖⼦列表
     */
    @ApiOperation("根据版块Id查询帖⼦列表")
    @GetMapping("/getAllByBoardId")
    public AppResult<List<Article>> getAllByBoardId(@ApiParam(value = "版块Id")
                                                    @RequestParam(value = "boardId", required = false) Long boardId) {
        // 定义返回的结果集对象
        List<Article> articles = null;
        // 根据传的参数返回不同板块的帖⼦列表
        if (boardId == null) {
            // 参数为空时表⽰⾸⻚帖⼦列表
            articles = articleService.selectAll();
            log.info("查询所有帖⼦列表");
        } else {
            // 参数i 为空时表⽰指定版本的帖⼦列表
            articles = articleService.selectAllByBoardId(boardId);
            log.info("查询版块帖⼦列表, boardId = " + boardId);
        }
        // 如果为null返回⼀个空JSON
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);
    }

    /**
     * 根据Id查询帖⼦详情
     *
     * @param id 版块Id
     * @return 指定Id的帖⼦详情
     */
    @ApiOperation("根据Id查询帖⼦详情")
    @GetMapping("/details")
    public AppResult<Article> getDetails(HttpServletRequest request,
                                         @ApiParam(value = "帖⼦Id")
                                         @RequestParam(value = "id") @NonNull Long id) {
        // 获取⽤⼾信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 调⽤Service层获取帖⼦详情
        Article article = articleService.selectDetailById(id);
        if(article==null){
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 当前⽤⼾是否作者
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        // 返回结果
        return AppResult.success(article);
    }

    @ApiOperation("编辑帖⼦")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request,
                            @ApiParam(value = "帖⼦Id") @RequestParam(value = "id") @NonNull Long id,
                            @ApiParam(value = "⽂章标题") @RequestParam(value = "title") @NonNull String title,
                            @ApiParam(value = "帖⼦内容") @RequestParam(value = "content") @NonNull String content) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 获取帖⼦原始数据
        Article article = articleService.selectById(id);
        if (article == null) {
            log.warn("修改的帖⼦不存在. articleId = " + id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 发帖⼈不是当前⽤⼾
        if (article.getUserId() != user.getId()) {
            log.warn(MessageFormat.format("发帖⼈不是当前⽤⼾. article id = {0}, article user id = {1}, " +
                    "current user id = {2}", article.getId(), article.getUserId(), user.getId()));
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        // 帖⼦状态异常 - 已归档
        if (article.getState() != 0 || article.getDeleteState() != 0) {
            log.warn("帖⼦状态异常. articleId = " + id + ", state = " +
                    article.getState() + ", delete state = " + article.getDeleteState());
            return AppResult.failed(ResultCode.FAILED_ARTICLE_BANNED);
        }
        // 调⽤业务层
        articleService.modify(id, title, content);
        log.info(MessageFormat.format("帖⼦修改成功. id = {0}, user id = {1}, 原标题 = {2}, 新标题 = {3}"
                , id, user.getId(), article.getTitle(), title));

        return AppResult.success();
    }

    @ApiOperation("点赞")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request,
                              @ApiParam(value = "帖⼦Id") @RequestParam(value = "id") @NonNull Long id) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断是否被禁⾔
        if (user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + ", userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    /**
     * 根据Id删除帖⼦
     *
     * @param id 帖⼦Id
     * @return
     */
    @ApiOperation("删除帖⼦")
    @PostMapping("/delete")
    public AppResult deleteById (HttpServletRequest request, @ApiParam("帖⼦Id") @RequestParam("id") @NonNull Long id) {
        // 1. ⽤⼾是否禁⾔
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Article article = articleService.selectById(id);
        // 2. 帖⼦是否存在或已删除
        if (article == null || article.getDeleteState() == 1) {
            return AppResult.failed(ResultCode.FAILED_ARTICLE_NOT_EXISTS);
        }
        // 3. ⽤⼾是否是作者
        if (article.getUserId() != user.getId()) {
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 调⽤Service执⾏删除
        articleService.deleteById(id);
        return AppResult.success();
    }

    /**
     * 根据⽤⼾Id查询帖⼦列表
     *
     * @param userId ⽤⼾Id
     * @return 指定版块的帖⼦列表
     */
    @ApiOperation("根据⽤⼾Id查询帖⼦列表")
    @GetMapping("/getAllByUserId")
    public AppResult<List<Article>> getAllByUserId (HttpServletRequest request ,
                                                    @ApiParam("用户Id") @RequestParam(value = "userId", required = false) Long userId) {
        // 如果UserId为空，那么从session中获取当前登录的用户id
        if(userId==null){
            HttpSession session=request.getSession(false);
            User user=(User) session.getAttribute(AppConfig.USER_SESSION);
            userId=user.getId();
        }
        // 查询⽤⼾的帖⼦列表
        List<Article> result = articleService.selectByUserId(userId);
        log.info("查询⽤⼾帖⼦列表, userId = " + userId);
        return AppResult.success(result);
    }

}
